package cn.onlineoedering.user.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.onlineoedering.common.util.CommonXmlUtil;
import cn.onlineoedering.common.util.HibernateUtil;
import cn.onlineoedering.user.dao.UserDao;
import cn.onlineoedering.user.entity.GeneralUser;
import cn.onlineoedering.user.entity.queryEntity.QueryUserDo;

/**
 * @author userDao
 * 
 */
public class UserDaoImpl implements UserDao {
	private Session session = HibernateUtil.getSession();

	/* 
	 * 保存用户到xml文件中
	 */
	public void saveTOXml(GeneralUser generalUser, String path) {
		CommonXmlUtil.saveUserToXml(path, generalUser);
	}

	/**
	 * 持久化用户
	 */
	public void save(GeneralUser generalUser) {
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(generalUser);
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	/**
	 * @param generalUser
	 * @return 用户实例
	 */
	public GeneralUser queryByName(String name) {
		try {
			Query query=session.createQuery("from GeneralUser where userName=?").setString(0, name);
			return (GeneralUser) query.uniqueResult();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			session.close();
		}
		
	}

	public void delete(long id) {
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.delete(session.get(GeneralUser.class, id));
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	public void update(GeneralUser generalUser) {
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.update(generalUser);
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	public QueryUserDo queryAll(Integer startPage, Integer endPage) {

		@SuppressWarnings("unchecked")
		List<GeneralUser> list = session.createQuery("from generalUser")//
				.setFirstResult(startPage)//
				.setMaxResults(endPage)//
				.list();
		long count = (Long) session.createQuery(
				"select count(*) from generalUser").uniqueResult();
		return new QueryUserDo(count, list);
	}

	@SuppressWarnings("unchecked")
	public List<GeneralUser> queryAll() {
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			List<GeneralUser> users = session.createQuery("from GeneralUser")
					.list();
			transaction.commit();
			return users;
		} catch (RuntimeException e) {
			transaction.rollback();
			throw e;
		} finally {
			session.close();
		}
	}

	/* 
	 * 向xml文件中查询
	 */
	public void queryToXml(GeneralUser user, String path) {
		
	}

}
